import asyncio
import time
import websockets


async def handle_message(websocket, path):
    _time = time.time()
    while True:
        message = await websocket.recv()
        # print(f"Received message: {message}")
        response = ''
        if str(message) == '2':
            # 模拟回复心跳消息
            response = '3'
        elif 'message' in str(message):
            # 模拟回复message消息
            response = f"Message received: {str(message)}"
        elif 'userList' in str(message):
            # 模拟回复用户列表消息
            response = '{"method":"userList","data":"123"}'
        if time.time() - _time >= 1:
            # 模拟服务器发送其他消息（1次/s 非回复类的消息，如转发的消息，系统消息等）
            await websocket.send('{"method":"message","data":"22"}')
        if response:
            await websocket.send(response)


async def main():
    async with websockets.serve(handle_message, "localhost", 8765):
        await asyncio.Future()  # run forever


# 目前调试情况看到，因未处理断开链接情况，会有一些报错，但是不影响测试。
asyncio.run(main())
